package com.example.myapplication.book;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.example.day01.R;

public class BookSpActivity extends AppCompatActivity {
    Spinner sp_1,sp_2;
    //数据源
    String books[]={"三国演义","西游记","水浒传","红楼梦","聊斋志异"};
    String name[][]={{"诸葛亮","刘备","关羽","张飞"},
            {"唐僧","孙悟空","猪八戒","沙和尚"},
            {"松江", "武松", "李聪","豹子头","吴用"},
            {"贾宝玉","林黛玉","薛宝钗","王熙凤"},
            {"聂小倩","宁采臣","燕赤霞","黑山老妖"},
            };
    ArrayAdapter<String> bookAdapter;
    ArrayAdapter<String> nameAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_sp);
        sp_1=findViewById(R.id.book_sp1);
        sp_2=findViewById(R.id.book_sp2);

        //定义适配器

        bookAdapter = new ArrayAdapter<>(this, R.layout.item_book_sp, R.id.item_book_tv, books);
        //设置适配器
        sp_1.setAdapter(bookAdapter);
        //创建二级下拉列表的适配器

        nameAdapter = new ArrayAdapter<>(this, R.layout.item_book_sp, R.id.item_book_tv);
        sp_2.setAdapter(nameAdapter);
        //设置监听器
        sp_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //被选中的位置:position
                String arr[]=name[position];
                nameAdapter.clear();
                nameAdapter.addAll(arr);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
}
